<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\DeviceBaseChildModel;
use share\exception\ApiException;
use share\service\BaseModelService;
use share\service\IdMakerService;
use share\utils\Helper;

class DeviceBaseChildService extends BaseModelService
{

    public static function getModel()
    {
        return new DeviceBaseChildModel;
    }

    /**
     * 删除主设备下所有的子设备
     */
    public static function delByPid($pid){
        return self::delByFilter(['pid' => $pid]);
    }

    public static function getAllByPid($pid){
        return self::getAllByFilter(['pid' => $pid]);
    }

    /**
     * 更新主设备下的所有子设备
     */
    public static function upsetByMainDevice($pid, $subPk, $children)
    {        
        $children = Helper::arraySmartUnique($children);
        $origins = self::getAllByPid($pid);
        $delIds = [];
        $exists = [];
        $addItems = [];
        $tn = time();

        foreach ($origins as $origin) {
            if ($origin['pk'] != $subPk || !in_array($origin['dn'], $children)) {
                $delIds[] = $origin['id'];
            } else {
                $exists[] = $origin['dn'];
            }
        }

        foreach ($children as $item) {
            if (!in_array($item, $exists)) {
                $addItems[] = [
                    'pk' => $subPk,
                    'dn' => $item,
                    'pid' => $pid,
                    'created' => $tn,
                    'updated' => $tn,
                ];
            }
        }
        if (count($addItems) > 0) {            
            $subIds = IdMakerService::makeMutil(IdMakerService::NAME_OF_DEVICE_BASE, count($addItems));
            foreach ($subIds as $key => $id) {
                $addItems[$key]['id'] = $id;
            }
        }

        if (count($delIds) > 0) {
            self::delByFilter(['id' => ['in', $delIds]]);
        }

        if (count($addItems) > 0) {
            self::addBulk($addItems);
        }
    }

    /**
     * 页面查询条件
     */
    public static function buildCondition($filter)
    {
        $res = [];
        if (isset($filter['pk']) && !empty($filter['pk'])) {
            $res['pk'] = ['like', '%' . $filter['pk'] . '%'];
        }
        if (isset($filter['dn']) && !empty($filter['dn'])) {
            $res['dn'] = ['like', '%' . $filter['dn'] . '%'];
        }
        if (isset($filter['pid']) && $filter['pid']) {
            $res['pid'] = $filter['pid'];
        }
        return $res;
    }
}
